package cn.ciis.basic.plugin;

import cn.ciis.basic.kit.J2CacheKit;
import cn.hutool.core.io.FileUtil;
import com.jfinal.kit.LogKit;
import com.jfinal.kit.Prop;
import com.jfinal.kit.PropKit;
import com.jfinal.plugin.IPlugin;
import net.oschina.j2cache.CacheChannel;
import net.oschina.j2cache.CacheException;
import net.oschina.j2cache.J2CacheBuilder;
import net.oschina.j2cache.J2CacheConfig;

import java.io.IOException;

public class J2CachePlugin implements IPlugin {
    private static CacheChannel cache;
    private final static J2CacheBuilder builder;

    @Override
    public boolean start() {

        cache = builder.getChannel();
        J2CacheKit.init(cache);
        return true;
    }

    @Override
    public boolean stop() {
        cache.close();
        return true;
    }

    //private final static String CONFIG_FILE = "/j2cache.properties";

    static {
        String CONFIG_FILE;
        Prop prop = PropKit.useFirstFound("ciis-dev.properties","ciis-pro.properties");
        if (prop.getBoolean("devMode",false)) {
            CONFIG_FILE=PropKit.get("cacheFile","/j2cache_dev.properties");
        }else{
            CONFIG_FILE =PropKit.get("cacheFile","/j2cache.properties");
        }

        try {

            LogKit.error("文件是否存在:{}", FileUtil.exist(CONFIG_FILE));
            J2CacheConfig config = J2CacheConfig.initFromConfig(CONFIG_FILE);
            builder = J2CacheBuilder.init(config);
        } catch (IOException e) {
            throw new CacheException("Failed to load j2cache configuration " + CONFIG_FILE, e);
        }
    }

    /**
     * 关闭 J2Cache
     */
    public static void close() {
        builder.close();
    }
}